//
//  LHYTextFieldCopyView.h
//  DrawLine
//
//  Created by lhy on 2021/2/4.
//

#import "LHYTextFieldCopyView.h"

@implementation LHYTextFieldCopyView
{
    //坐标
    CGRect   _frame;
    //是否显示清空按钮
    BOOL     _clear;
    //设置leftView
    UIView   *_leftView;
    //设置字号
    CGFloat  _fontSize;
}

/**
 *  自定义初始化方法
 *
 *  @param frame       frame
 *  @param placeholder 提示语
 *  @param clear       是否显示清空按钮 YES为显示
 *  @param view        是否设置leftView不设置传nil
 *  @param font        设置字号
 *
 */
- (id)initWithFrame:(CGRect)frame placeholder:(NSString *)placeholder clear:(BOOL)clear leftView:(id)view fontSize:(CGFloat)font
{
    self = [super initWithFrame:frame];
    if (self) {
        _frame = frame;
        _clear = clear;
        _leftView = (UIView *)view;
        _fontSize = font;
        self.placeholder = placeholder;
        self.textColor = UIColor.clearColor;
        self.font = [UIFont systemFontOfSize:_fontSize];
        self.delegate = self;
        if (clear) {
            self.clearButtonMode = UITextFieldViewModeWhileEditing;
        }
        if (view) {
            self.leftView = view;
            self.leftViewMode = UITextFieldViewModeAlways;
        }
        [self becomeFirstResponder];
        [self createLabel];
        
        //移动手势
        UIPanGestureRecognizer *pgr = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pgr:)];
        [self addGestureRecognizer:pgr];
        //单击手势
        UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tgr:)];
        [self addGestureRecognizer:tgr];
    }
    return self;
}

//为了能接收到事件（能成为第一响应者），我们需要覆盖一个方法：
- (BOOL)canBecomeFirstResponder {
    return YES;
}
// 可以响应的方法
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    
    if (action == @selector(copyItem:) || action == @selector(deleteView:)) {
        return YES;
    }
    return NO;
}
//冒泡复制
- (void)copyItem:(id)sender {
    UIPasteboard *pboard = [UIPasteboard generalPasteboard];
    pboard.string = self.text;
    
    if (self.getCopyTextBlock) {
        CGRect copyRect = CGRectMake(self.frame.origin.x - 20, self.frame.origin.y - 20, self.frame.size.width, self.frame.size.height);
        self.getCopyTextBlock(pboard.string, copyRect);
    }
}
//冒泡删除
- (void)deleteView:(id)sender {
    if (self.removeTextBlock) {
        self.removeTextBlock(self);
    }
    [self removeFromSuperview];
}

/**
 *  创建label
 */
- (void)createLabel {
    _label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, _frame.size.width, _frame.size.height)];
    if (_leftView) {
        _label.frame = CGRectMake(_leftView.frame.size.width, _label.frame.origin.y, _label.frame.size.width - _leftView.frame.size.width, _label.frame.size.height);
    }
    if (_clear) {
        _label.frame = CGRectMake(_label.frame.origin.x, _label.frame.origin.y, _label.frame.size.width-20, _label.frame.size.height);
    }
    _label.backgroundColor = UIColor.clearColor;
    _label.font = [UIFont systemFontOfSize:_fontSize];
    _label.numberOfLines = 0;
    
    [self addSubview:_label];
}

#pragma mark - 手势
- (void)tgr:(UITapGestureRecognizer *)tgr {
    [self becomeFirstResponder];
}

- (void)pgr:(UIPanGestureRecognizer *)pgr {
    
    CGPoint touchPoint = [pgr locationInView:pgr.view.superview];
    self.center = touchPoint;
}

#pragma mark - UITextFieldDelegate
// 点击return回收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
// 将要编辑
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    NSLog(@"将要编辑");
    return YES;
}
// 开始编辑
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    NSLog(@"开始编辑");
    self.layer.borderWidth = 1;
    self.layer.borderColor = UIColor.blueColor.CGColor;
    self.borderStyle = UITextBorderStyleNone;
    
    NSArray *arr = @[@"复制", @"删除"];
    NSMutableArray *mArr = [[NSMutableArray alloc] init];
    UIMenuItem *copyKaoBeiItem = [[UIMenuItem alloc] initWithTitle:arr[0] action:@selector(copyItem:)];
    UIMenuItem *deleteItem = [[UIMenuItem alloc] initWithTitle:arr[1] action:@selector(deleteView:)];
    
    [mArr addObject:copyKaoBeiItem];
    [mArr addObject:deleteItem];
    
    [[UIMenuController sharedMenuController] setMenuItems:mArr];
    if (@available(iOS 13.0, *)) {
        [[UIMenuController sharedMenuController] showMenuFromView:self rect:self.bounds];
    } else {
        [[UIMenuController sharedMenuController] setTargetRect:self.bounds inView:self];
        [[UIMenuController sharedMenuController] setMenuVisible:YES animated:YES];
    }
}

- (void)textFieldDidChangeSelection:(UITextField *)textField {
    
    NSString *str = [NSString stringWithFormat:@"%@|",textField.text];
    CGSize size = [self labelText:str fondSize:_fontSize width:_label.frame.size.width];
    _label.frame = CGRectMake(_label.frame.origin.x,
                              _label.frame.origin.y,
                              _label.frame.size.width,
                              size.height < _frame.size.height ? _frame.size.height : size.height);
    
//    获取当前 textField 在父视图中的 frame
    CGRect newRect = [self convertRect:self.bounds toView:self.superview];
    
    self.frame = CGRectMake(newRect.origin.x,
                            newRect.origin.y,
                            _frame.size.width,
                            size.height < _frame.size.height ? _frame.size.height : size.height);
    
    if (textField.text.length == 0) {
        _label.text = @"";
        self.tintColor = [UIColor blueColor];
    } else {
        //添加一个假的光标
        self.tintColor = [UIColor clearColor];
        NSString *text = [NSString stringWithFormat:@"%@|", textField.text];
        NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:text];
        
        [attString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(text.length - 1, 1)];
        _label.attributedText = attString;
    }
}
//将要编辑完成
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    NSLog(@"textField将要编辑完成");
    return YES;
}
//编辑完成
- (void)textFieldDidEndEditing:(UITextField *)textField {
    NSLog(@"textField编辑完成");
    [self resignFirstResponder];
    
    self.backgroundColor = UIColor.clearColor;
//    self.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.5];
    self.layer.borderWidth = 0;
}
//点击键盘调用
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSLog(@"点击键盘调用");
    return YES;
}
//点击清空按钮
- (BOOL)textFieldShouldClear:(UITextField *)textField {
    NSLog(@"textField清空");
    _label.text = @"";
    return YES;
}
/**
 *  计算字符串长度，UILabel自适应高度
 *
 *  @param text  需要计算的字符串
 *  @param size  字号大小
 *  @param width 最大宽度
 *
 *  @return 返回大小
 */
- (CGSize)labelText:(NSString *)text fondSize:(float)size width:(CGFloat)width {
    NSDictionary *send = @{NSFontAttributeName: [UIFont systemFontOfSize:size]};
    CGSize textSize = [text boundingRectWithSize:CGSizeMake(width, 0)
                                         options:NSStringDrawingTruncatesLastVisibleLine |
                       NSStringDrawingUsesLineFragmentOrigin |
                       NSStringDrawingUsesFontLeading
                                      attributes:send context:nil].size;
    
    return textSize;
}

- (void)setPageIndex:(NSInteger)pageIndex {
    _pageIndex = pageIndex;
}


@end
